package com.slipper.ai.controller;

import com.slipper.ai.flow.FlowEngine;
import com.slipper.ai.flow.Parser;
import com.slipper.ai.flow.vo.FlowVO;
import com.slipper.ai.vo.FlowChartVO;
import com.slipper.system.ai.bo.AiFlowBO;
import com.slipper.system.ai.service.AiFlowService;
import com.slipper.util.ResultUtil;
import com.slipper.util.Tool;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/ai/flow")
public class AiFlowApiController {
    @Resource
    private FlowEngine flowEngine;
    @Resource
    private AiFlowService aiFlowService;

    @PostMapping(value = "/debug")
    public String debug(@RequestBody FlowChartVO vo) {
        String jsonText = null;
        if (Tool.isNotBlank(vo.getFlowId())) {
            AiFlowBO flowBO = aiFlowService.queryBy(vo.getFlowId());
            jsonText = flowBO.getJsonText();
        } else if (Tool.isNotBlank(vo.getFlowJsonText())) {
            jsonText = vo.getFlowJsonText();
        }
        if (Tool.isBlank(jsonText)) {
            return ResultUtil.failureResult("请先配置流程！");
        }

        FlowVO flowVO = Parser.parse(jsonText);
        if (flowVO == null) return ResultUtil.failureResult("流程配置解释出错！");

        flowVO.setSessionId(vo.getSessionId());
        flowVO.setFlowData(vo.getChartData());
        return ResultUtil.successResult(flowEngine.start(flowVO));
    }
}
